<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <title>上传防溺水防控人员照片</title>
    <link rel="stylesheet" href="./style/weui.css"/>
    <link rel="stylesheet" href="./style/example.css"/>
    <link rel="stylesheet" href="./style/jquery-weui.min.css">
    <link rel="stylesheet" href="./style/my.css">
    <link rel="stylesheet" type="text/css" href="./static/mobile/css/wx/style.css" />
    <link rel="stylesheet" type="text/css" href="./static/assets/layui/css/layui.css" />
    <style>
        /*.weui-cells{
            background: #fff !important;
        }*/
    </style>
</head>
<body>
<div class="page js_show home">
    <div style="font-size:30px;text-align: center;margin-top:20px;margin-bottom: 20px;">
        上传防溺水防控人员照片
    </div>
    <div class="weui-form__control-area">
        <div class="weui-cells__group weui-cells__group_form">
            <div class="weui-cells weui-cells_form">
                <div class="weui-cell weui-cell_active">
                    <div class="weui-cell__hd"><label class="weui-label">姓名:</label></div>
                    <div class="weui-cell__bd">
                        <input id="name" class="weui-input" placeholder="请填写姓名" type="text" value=""/>
                    </div>
                </div>
                <div class="weui-cell weui-cell_active">
                    <div class="weui-cell__hd"><label class="weui-label">联系电话</label></div>
                    <div class="weui-cell__bd">
                        <input id="tel" class="weui-input" placeholder="请填写联系电话" value="" type="number" pattern="[0-9]*"/>
                    </div>
                </div>
                <div class="weui-cell weui-cell_active">
                    <div class="weui-cell__hd"><label class="weui-label">上传照片：</label></div>
                    <div class="weui-cell__bd" style="display: block;">
                        <div class="device_detail" style="">
                            
                            <div class="layui-upload" style="width: 100px;">
                                <div class="layui-upload-list" id="demo1" style="width: 100%; height:100px;">
                                    <img src="" height="100" style="display: none;" />
                                    <input type="hidden" id="thumb_pic" name="thumb" value="">
                                </div>
                            </div>
                            <div style="width:100px">
                                <button type="button" class="layui-btn layui-btn-normal" style="width: 100%;border-radius: 20px;" id="uploadBtn">上传照片</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div style="color:red; font-size: 14px;margin-left:20px;margin-top:0px">
                建议照片使用1寸电子照片，小于500K。
            </div>
            <div class="button-sp-area" style="margin-top:65px;">
                <a href="javascript:" class="weui-btn weui-btn_primary" id="weui-btn_update">提交</a>
            </div>
        </div>
    </div>
</div>

<script src="./js/jquery.min.js"></script>
<script src="./js/jquery-weui.min.js"></script>
<script src="./js/zepto.min.js?a=1"></script>
<script src="./js/jweixin-1.0.0.js"></script>
<script src="./js/weui.min.js"></script>
<script src="./static/mobile/js/jquery2.min.js"></script>
<script src="./static/mobile/js/layer/layer.js"></script>
<script src="./static/assets/layui/layui.js"></script>
<script src="./static/assets/gougu/gouguInit.js"></script>
<script src='./static/mobile/js/wx/jweixin-1.4.0.js'></script>
<script src='./static/mobile/js/wx/recharge.js?v=2'></script>
<script src="./static/mobile/js/wx/jquery.cookie.js"></script>
<script>
    const moduleInit = ['tool','layer', 'form', 'upload'];
    function gouguInit() {
        var form = layui.form, tool = layui.tool, upload = layui.upload;

        // 头像上传
        var uploadInst = upload.render({
            elem: '#uploadBtn'
            //, url: 'http://60.217.22.201:8501/api/video/uploads'
            ,accept: 'images'
            ,auto: false // 禁止自动上传
            ,multiple: true
            , before: function(obj) { // 上传前的回调
                // 显示加载效果
                layer.load(1);
            }
            , choose: function(obj) {
                // 读取图片文件
                var files = Object.entries(obj.pushFile())[0][1];
                console.log(obj);
                console.log(files);
                console.log(files instanceof Blob);
                if (files) {
                    var file = files;
                    if (file && file instanceof Blob) {
                        compressImage(file, function(compressedFile) {
                            // 替换原始文件
                            /*var newFileList = new DataTransfer();
                            newFileList.items.add(compressedFile);
                            console.log(newFileList.files[0]);
                            obj.files[0] = newFileList.files[0];

                            // 继续上传
                            obj.upload();*/
                            var formData = new FormData();
                            console.log(compressedFile);
                            console.log(compressedFile.name);
                            formData.append('file', compressedFile, compressedFile.name);
                            uploadCompressedFile(formData);
                            console.log(formData);
                        });
                    } else {
                        layer.msg('文件选择错误');
                    }
                    /*if (file && file instanceof Blob) {
                        var reader = new FileReader();
                        reader.onload = function(e) {
                            var img = new Image();
                            img.src = e.target.result;
                            img.onload = function() {
                                var canvas = document.createElement('canvas');
                                var ctx = canvas.getContext('2d');
                                var maxWidth = 800; // 最大宽度
                                var maxHeight = 800; // 最大高度
                                var width = img.width;
                                var height = img.height;

                                // 计算新的尺寸
                                if (width > height) {
                                    if (width > maxWidth) {
                                        height *= maxWidth / width;
                                        width = maxWidth;
                                    }
                                } else {
                                    if (height > maxHeight) {
                                        width *= maxHeight / height;
                                        height = maxHeight;
                                    }
                                }

                                canvas.width = width;
                                canvas.height = height;
                                ctx.drawImage(img, 0, 0, width, height);
                                // 将画布内容转换为Blob
                                canvas.toBlob(function(blob) {
                                    // 创建一个新的File对象
                                    var newFile = new File([blob], file.name, {
                                        type: file.type,
                                        lastModified: Date.now()
                                    });
                                    callback(newFile);
                                }, file.type, 0.5); // 设置质量参数为0.8
                                // 将画布内容转换为Blob
                                canvas.toBlob(function(blob) {
                                    // 创建一个新的File对象
                                    var newFile = new File([blob], file.name, {
                                        type: file.type,
                                        lastModified: Date.now()
                                    });
                                    console.log(newFile);
                                    console.log(obj);
                                    obj.item[0]=[];
                                    // 替换原始文件
                                    var newFileList = new DataTransfer();
                                    newFileList.items.add(newFile);
                                    console.log(newFileList);
                                    obj.item[0] = newFileList.files[0];

                                    // 继续上传
                                    obj.upload();
                                }, file.type);
                            };
                        };
                        reader.readAsDataURL(file);
                    } else {
                        layer.msg('文件选择错误');
                    }*/
                } else {
                    layer.msg('请选择文件');
                }
                return false; // 阻止默认上传
                // 读取图片文件
                //var files = obj.pushFile();
                /*var files = this.file = obj.pushFile()
                console.log(files); // 打印文件对象
                console.log(files.length); // 打印文件对象
                console.log(files[0]); // 打印文件对象
                obj.preview(function (index, file, result) {
                    files = Object.keys(files);
                    console.log(files);
                     if (files && files.length > 0) {
                        var file = files[0];
                        if (file && file instanceof Blob) {
                            compressImage(file, function(compressedFile) {
                                // 替换原始文件
                                var newFileList = new DataTransfer();
                                newFileList.items.add(compressedFile);
                                obj.item[0] = newFileList.files[0];

                                // 继续上传
                                obj.upload();
                            });
                        } else {
                            layer.msg('文件选择错误');
                        }
                    } else {
                        layer.msg('请选择文件');
                    }
                    return false; // 阻止默认上传

                });
                if (files && files.length > 0) {
                    var file = files[0];
                    if (file && file instanceof Blob) {
                        compressImage(file, function(compressedFile) {
                            // 替换原始文件
                            var newFileList = new DataTransfer();
                            newFileList.items.add(compressedFile);
                            obj.item[0] = newFileList.files[0];

                            // 继续上传
                            obj.upload();
                        });
                    } else {
                        layer.msg('文件选择错误');
                    }
                } else {
                    layer.msg('请选择文件');
                }
                return false; // 阻止默认上传*/
            }
            , done: function(e) {
                // 隐藏加载效果
                layer.closeAll('loading');

                // 如果上传失败
                if (e.code == 1) {
                    return layer.msg('上传失败');
                }
                layer.msg('上传成功');
                $('#demo1 img').show();
                // 上传成功
                $('#demo1 input').attr('value', 'http://60.217.22.201:8501' + e.data.filepath);
                $('#demo1 img').attr('src', 'http://60.217.22.201:8501' + e.data.filepath);
            }
            , error: function() {
                // 隐藏加载效果
                layer.closeAll('loading');
                layer.msg('上传失败');
            }
        });

        $('#weui-btn_update').on('click', function() {
            var name = $("#name").val();
            if (name.length <= 0 || name.length > 8) {
                layer.msg('请检查姓名');
                return false;
            }
            var tel = $("#tel").val();
            if (tel.length <= 0 || tel.length != 11) {
                layer.msg('请检查联系方式');
                return false;
            }
            var img = $('#thumb_pic').val();
            if (img.length <= 0) {
                layer.msg('请检查图片');
                return false;
            }
            var pinjie ='此信息确认提交? <br>姓名：'+name+'</br>联系方式：'+tel
            layer.confirm(pinjie, {
              btn: ['确认', '取消'] //可以无限个按钮
              ,btn1: function(index, layero){
                alert(index);
              }
            }, function(index){
              //按钮【按钮二】的回调
                layer.close(index)
                let index2 = layer.load(1);
                $.ajax({
                    url: 'http://60.217.22.201:8501/api/video/addface', // 后端接口 URL
                    type: 'POST',
                    data: {
                        name: name,
                        contact: tel,
                        face_img: img,
                    },
                    success: function(res) {
                        layer.msg(res.msg);
                        if (res.code == 0) {
                            location.href = "success.html";
                        } else {
                            // location.href="warn.html";
                        }
                        layer.close(index2);
                    }
                    /*,
                    error: function(error) {
                        layer.msg(error.msg);
                        layer.close(index);
                    }*/
                });
                
            });
            //return false;
            
        });
    }
    // 上传压缩后的文件的函数
  function uploadCompressedFile(formData) {
    // 使用 AJAX 或 Fetch API 发送 FormData 对象
    $.ajax({
      url: 'http://60.217.22.201:8501/api/video/upload', // 替换为你的上传 URL
      type: 'POST',
      data: formData,
      processData: false, // 告诉 jQuery 不要去处理发送的数据
      contentType: false, // 告诉 jQuery 不要去设置 Content-Type 请求头
      success: function(e) {
        // 处理上传成功的情况
        

        // 如果上传失败
        if (e.code == 1) {
            layer.closeAll('loading');
            layer.msg('上传失败');
            //layer.msg(e.msg);
            return false;
        }
        
        $('#demo1 img').show();
        // 上传成功
        $('#demo1 input').attr('value', 'http://60.217.22.201:8501' + e.data.filepath);
        $('#demo1 img').attr('src', 'http://60.217.22.201:8501' + e.data.filepath);
        layer.closeAll('loading');
        layer.msg('上传成功');
        // ... 其他逻辑 ...
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // 处理上传失败的情况
        layer.msg('上传失败');
        // ... 其他逻辑 ...
      },
      complete: function() {
        // 上传完成后执行的逻辑（无论成功还是失败）
        // 隐藏加载层等
      }
    });
  }
    function compressImage(file, callback) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = new Image();
            img.src = e.target.result;
            img.onload = function() {
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var maxWidth = 200; // 最大宽度
                var maxHeight = 200; // 最大高度
                var width = img.width;
                var height = img.height;

                // 计算新的尺寸
                if (width > height) {
                    if (width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    }
                } else {
                    if (height > maxHeight) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }
                }

                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);

                // 将画布内容转换为Blob
                canvas.toBlob(function(blob) {
                    // 创建一个新的File对象
                    var newFile = new File([blob], file.name, {
                        type: file.type,
                        lastModified: Date.now()
                    });
                    callback(newFile);
                }, file.type, 0.3); // 设置质量参数为0.8
            };
        };
        reader.readAsDataURL(file);
    }
</script>
</body>
</html>